package com.stn.zjx.givingtreasure.activity.dynamic;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.irozon.sneaker.Sneaker;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.common.DropImgsShowActivity;
import com.stn.zjx.givingtreasure.adapter.DynamicGuestAdapter;
import com.stn.zjx.givingtreasure.adapter.DynamicRecommandListAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.DynamicDetailDomain;
import com.stn.zjx.givingtreasure.domain.DynamicGuestDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicGuestNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicLikeNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserFollowNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.OpenLocalMapUtil;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxImageTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

@SuppressWarnings("all")
public class DynamicDetailActivity extends BaseActivity implements AMapLocationListener {
    private static final int PRC_PHOTO_PICKER = 1010;
    public Integer id = 0;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.like_iv)
    ImageView likeIv;
    @BindView(R.id.like_bt)
    LinearLayout likeBt;
    @BindView(R.id.guest_iv)
    ImageView guestIv;
    @BindView(R.id.guest_bt)
    LinearLayout guestBt;
    @BindView(R.id.open_guest)
    LinearLayout openGuest;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.cir)
    CircleImageView cir;
    @BindView(R.id.sex)
    ImageView sex;
    @BindView(R.id.head_1)
    RelativeLayout head1;
    @BindView(R.id.follow_bt)
    Button followBt;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.date_time)
    TextView dateTime;
    @BindView(R.id.blue_location_iv)
    ImageView blueLocationIv;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.nav_location)
    RelativeLayout navLocation;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.see_count)
    TextView seeCount;
    @BindView(R.id.img_ll)
    LinearLayout imgLl;
    @BindView(R.id.like_tv)
    TextView likeTv;
    @BindView(R.id.re_command_rv)
    RecyclerView reCommandRv;
    @BindView(R.id.no_data)
    LinearLayout noData;
    @BindView(R.id.bottom_loading_tv)
    TextView bottomLoadingTv;
    @BindView(R.id.bottom_loading)
    RelativeLayout bottomLoading;
    @BindView(R.id.new_update_rv)
    RecyclerView newUpdateRv;
    @BindView(R.id.new_update_title)
    TextView newUpdateTitle;
    @BindView(R.id.hot_title)
    TextView hotTitle;
    @BindView(R.id.hot_rv)
    RecyclerView hotRv;
    @BindView(R.id.up_layout)
    LinearLayout upLayout;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.rootView)
    LinearLayout rootView;
    private BadgeView badgeView;
    DynamicRecommandListAdapter recommandListAdapter;
    private LinearLayoutManager rc;
    private LinearLayoutManager new_updaet_rc;
    private DynamicGuestAdapter newUpdateAdpater;
    private LinearLayoutManager hot_rc;
    private DynamicGuestAdapter hotAdpater;
    public int pageNow = 1;
    public int pageSize = 10;
    public boolean isMoreLoading = false;
    public boolean isOpenKeywowrd = false;
    public String city = "";
    public String area = "";
    public double longitude = 0;
    public double latitude = 0;
    public String fromAddress = "";

    public AmapLocationService amapLocationService = null;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    //登录刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFragmentLoginRefresh(RefreshEvent event) {
        if (event.flag == RefreshEvent.LOGIN_REFRESH) {
            initInfo();
            initData();
        } else if (event.flag == RefreshEvent.REFRESH) {
            initData();
        }
    }

    @Override
    public void initComponent() {
        shareBt.setVisibility(View.VISIBLE);
        id = getIntent().getIntExtra("id", 0);
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > ToolsUtils.dip2px(getApplicationContext(), 40)) {
                    actionTitle.setText(userNickname.getText().toString().trim());
                } else {
                    actionTitle.setText("");
                }

                if (scrollY == (nestedScrollView.getChildAt(0).getMeasuredHeight() - nestedScrollView.getMeasuredHeight())) {

                    if (!isMoreLoading && newUpdateAdpater.dataBeanList.size() >= pageNow * pageSize) {
                        User onlineUser = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
                        String token = "";
                        if (onlineUser == null) {
                            token = "";
                        } else {
                            token = onlineUser.getToken();
                        }
                        query_new_update_dynamic_guest_append(token, id);
                    }
                }

            }
        });
        badgeView = BadgeFactory.create(this)
                .setTextColor(getResources().getColor(R.color.white))
                .setWidthAndHeight(15, 15)
                .setBadgeBackground(getResources().getColor(R.color.red))
                .setTextSize(8)
                .setMargin(10, 0, 0, 5)
                .setBadgeGravity(Gravity.RIGHT | Gravity.TOP)
                .setBadgeCount("0")
                .setShape(BadgeView.SHAPE_CIRCLE)
                .bind(guestIv);
        rc = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        reCommandRv.setLayoutManager(rc);
        recommandListAdapter = new DynamicRecommandListAdapter(this);
        reCommandRv.setAdapter(recommandListAdapter);

        new_updaet_rc = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        newUpdateRv.setLayoutManager(new_updaet_rc);
        newUpdateAdpater = new DynamicGuestAdapter(this);
        newUpdateRv.setAdapter(newUpdateAdpater);

        hot_rc = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        hotRv.setLayoutManager(hot_rc);
        hotAdpater = new DynamicGuestAdapter(this);
        hotRv.setAdapter(hotAdpater);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_detail);
        ButterKnife.bind(this);
        initComponent();
//        initGuestDialog();
        initInfo();
        initData();

    }


    public void initGuestDialog() {
        Dialog guest_dialog;
        EditText guest_content_edit;
        guest_dialog = new Dialog(this, R.style.dialog_soft_input);
        guest_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        guest_dialog.setContentView(R.layout.dialog_dynamic_guest_input);
        WindowManager.LayoutParams lp = guest_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.BOTTOM;
        guest_dialog.getWindow().setAttributes(lp);

        guest_content_edit = guest_dialog.findViewById(R.id.content_edit);
        TextView guest_num_count = guest_dialog.findViewById(R.id.num_count);
        TextView guest_send_guest_bt = guest_dialog.findViewById(R.id.send_guest_bt);
        View exit_bt = guest_dialog.findViewById(R.id.exit_bt);
        exit_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                guest_dialog.dismiss();
            }
        });
        guest_dialog.findViewById(R.id.rootView)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        guest_dialog.dismiss();
                    }
                });
        guest_content_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                guest_num_count.setText(guest_content_edit.getText().length() + "/100");
                if (guest_content_edit.getText().length() == 0) {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                    guest_send_guest_bt.setClickable(false);
                } else {
                    guest_send_guest_bt.setBackgroundResource(R.drawable.focus_theme_5dp);
                    guest_send_guest_bt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                    guest_send_guest_bt.setClickable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        guest_send_guest_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User onlineUser = UserService
                        .getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                    return;
                }
                send_dynamic_guest(onlineUser.getToken(),
                        id,
                        guest_content_edit.getText().toString().trim(), guest_dialog);

            }
        });
        guest_send_guest_bt.setClickable(false);
        guest_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //    guest_content_edit.getText().clear();
                // 显示软键盘
                guest_content_edit.requestFocus();
                SoftInputUtils.openSoftInput(DynamicDetailActivity.this, guest_dialog.getCurrentFocus(), 50);


                //  SoftInputUtils.showSoftInput(DynamicDetailActivity.this,guest_dialog);
            }
        });
        guest_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                SoftInputUtils.closedSoftInput(DynamicDetailActivity.this);
//                im.hideSoftInputFromWindow(guest_content_edit.getWindowToken(),0);
                guest_content_edit.getText().clear();
            }
        });
        guest_dialog.show();
    }

    @OnClick({R.id.back_bt, R.id.share_bt,R.id.open_guest, R.id.guest_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share_bt:
                Bitmap bitmap = ToolsUtils.getBitmapByView(rootView);
                savetoImg(bitmap);
                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.open_guest:
                User onlineUser = UserService
                        .getInstance(this)
                        .getOnlineLoginUser();
                if (onlineUser == null) {
                    RxActivityTool.skipActivity(this, UserLoginActivity.class);
                    return;
                }
                initGuestDialog();
                break;
            case R.id.guest_bt:
                nestedScrollView.smoothScrollTo(0, upLayout.getMeasuredHeight());
                break;

        }
    }


    public void initInfo() {
        amapLocationService = new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.start();
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        String token = "";
        if (onlineUser == null) {
            token = "";
        } else {
            token = onlineUser.getToken();
        }
        UserDynamicNetImpl
                .query_dynamic_detail(token, id, id + "query_dynamic_detail_" + token, new StringCallback() {
                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            initDynamicDetailResult(response.body());
                        }
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            initDynamicDetailResult(response.body());
                        }

                    }
                });

    }

    public void initData() {
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        String token = "";
        if (onlineUser == null) {
            token = "";
        } else {
            token = onlineUser.getToken();
        }
        query_new_update_dynamic_guest(token, id);
    }


    public void initDynamicDetailResult(String body) {
        DynamicDetailDomain domain = new Gson().fromJson(body, DynamicDetailDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                Glide
                        .with(DynamicDetailActivity.this)
                        .asDrawable()
                        .apply(new RequestOptions().placeholder(R.mipmap.default_avatar))
                        .load(domain.getData().getDetailData().getUserAvatar())
                        .into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                cir.setImageDrawable(resource);
                            }
                        });
                userNickname.setText(domain.getData().getDetailData().getUserNickname());
                switch (domain.getData().getDetailData().getUserSex()) {
                    case 0:
                        sex.setVisibility(View.GONE);
                        break;
                    case 1:
//                        sex.setVisibility(View.VISIBLE);
//                        sex.setImageResource(R.mipmap.male);
                        break;
                    case 2:
//                        sex.setVisibility(View.VISIBLE);
//                        sex.setImageResource(R.mipmap.female);
                        break;
                }
                if (domain.getData().getDetailData().getLocationLongitude() != 0 &&
                        domain.getData().getDetailData().getLocationLatitude() != 0
                        && longitude != 0 && longitude != 0) {
                    navLocation.setVisibility(View.VISIBLE);
                    address.setText(domain.getData().getDetailData().getDynamicAddress());
                    navLocation.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
//                            Bundle bundle = new Bundle();
//                            bundle.putString("url", WebApi.location_nav_map + "?locationLongitude=" + domain.getData().getDetailData()
//                                    .getLocationLongitude() + "&&locationLatitude=" + domain.getData().getDetailData().getLocationLatitude());
//                            RxActivityTool.skipActivity(getApplicationContext(), GenericWebActivity.class, bundle);
                            openMapDialog(fromAddress + "", domain.getData().getDetailData().getDynamicAddress(), String.valueOf(longitude),
                                    String.valueOf(latitude),
                                    String.valueOf(domain.getData().getDetailData().getLocationLongitude()),
                                    String.valueOf(domain.getData().getDetailData().getLocationLatitude())
                            );
                        }
                    });
                } else {
                    navLocation.setVisibility(View.GONE);
                }
                dateTime.setText(ToolsUtils.getDateBeforeAfter(domain.getData().getDetailData().getDynamicCreatedate()));
                seeCount.setText(ToolsUtils.getSeecount(domain.getData().getDetailData().getDynamicSeeCount()));
                if (domain.getData().getDetailData().getIsFollow() == 0) {
                    followBt.setBackgroundResource(R.drawable.focus_blue_5dp);
                    followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                    followBt.setText(getString(R.string.follow));
                } else {
                    followBt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                    followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                    followBt.setText(getString(R.string.already_follow));
                }
                followBt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        User onlineUser = UserService
                                .getInstance(getApplicationContext())
                                .getOnlineLoginUser();
                        if (onlineUser == null) {
                            RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                            return;
                        }
                        if (domain.getData().getDetailData().getIsFollow() == 0) {
                            followBt.setBackgroundResource(R.drawable.focus_light_gray_5dp);
                            followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.gray));
                            followBt.setText(getString(R.string.already_follow));
                            domain.getData().getDetailData().setIsFollow(1);
                            set_follow(onlineUser.getToken(), domain.getData().getDetailData().getUserId());
                        } else {
                            followBt.setBackgroundResource(R.drawable.focus_blue_5dp);
                            followBt.setTextColor(ActivityCompat.getColor(getApplicationContext(), R.color.white));
                            followBt.setText(getString(R.string.follow));
                            domain.getData().getDetailData().setIsFollow(0);
                            set_no_follow(onlineUser.getToken(), domain.getData().getDetailData().getUserId());
                        }
                    }
                });
                String[] orign_imgs = domain.getData().getDetailData().getDynamicImgs().split("\\*");
                List<String> new_imgs = new ArrayList<>();
                for (int o = 0; o < orign_imgs.length; o++) {
                    if (!TextUtils.isEmpty(orign_imgs[o])) {
                        new_imgs.add(orign_imgs[o]);
                    }
                }
                imgLl.removeAllViews();
                for (int i = 0; i < new_imgs.size(); i++) {
                    String img = new_imgs.get(i);
                    ImageView iv = new ImageView(getApplicationContext());
                //    iv.setMaxHeight(ToolsUtils.dip2px(getApplicationContext(), 250));
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);
              //      iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                //    iv.setAdjustViewBounds(true);
                    lp.leftMargin = ToolsUtils.dip2px(getApplicationContext(), 15);
                    lp.rightMargin = ToolsUtils.dip2px(getApplicationContext(), 15);
                    lp.topMargin = ToolsUtils.dip2px(getApplicationContext(), 10);
                    iv.setLayoutParams(lp);
                    Glide.with(DynamicDetailActivity.this)
                            .asDrawable()
                            .apply(new RequestOptions().placeholder(new ColorDrawable(ActivityCompat.getColor(getApplicationContext(), R.color.light_gray))))
                            .load(img)
                            .into(new SimpleTarget<Drawable>() {
                                @Override
                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                    iv.setImageDrawable(resource);

                                }
                            });

                    int finalI = i;
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(getApplicationContext(), DropImgsShowActivity.class);
                            int[] location = new int[2];
                            iv.getLocationOnScreen(location);
                            intent.putExtra("left", location[0]);
                            intent.putExtra("top", location[1]);
                            intent.putExtra("height", iv.getHeight());
                            intent.putExtra("width", iv.getWidth());
                            intent.putExtra("position", finalI);
                            intent.putStringArrayListExtra("imgs", (ArrayList<String>) new_imgs);
                            overridePendingTransition(0, 0);
                            startActivity(intent);
                        }
                    });
                    imgLl.addView(iv);
                }
                if (domain.getData().getDetailData().getGuestCount() >= 99) {
                    badgeView.setBadgeCount("99+");
                } else {
                    badgeView.setBadgeCount("" + domain.getData().getDetailData().getGuestCount());
                }
                content.setText(domain.getData().getDetailData().getDynamicContent());


                switch (domain.getData().getDetailData().getIsLike()) {
                    case 0:
                        likeIv.setImageResource(R.mipmap.no_like);
                        likeTv.setText(getString(R.string.like));
                        break;
                    case 1:
                        likeIv.setImageResource(R.mipmap.yes_like);
                        likeTv.setText(getString(R.string.alreay_like));
                        break;
                }

                likeBt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        User onlineUser = UserService
                                .getInstance(getApplicationContext())
                                .getOnlineLoginUser();
                        if (onlineUser == null) {
                            RxActivityTool.skipActivity(getApplicationContext(), UserLoginActivity.class);
                            return;
                        }
                        switch (domain.getData().getDetailData().getIsLike()) {
                            case 0:
                                likeIv.setImageResource(R.mipmap.yes_like);
                                domain.getData().getDetailData().setIsLike(1);
                                set_dynamic_like(onlineUser.getToken(), domain.getData().getDetailData().getUserDynamicId());
                                likeTv.setText(getString(R.string.alreay_like));
                                break;
                            default:
                                likeIv.setImageResource(R.mipmap.no_like);
                                domain.getData().getDetailData().setIsLike(0);
                                set_dynamic_no_like(onlineUser.getToken(), domain.getData().getDetailData().getUserDynamicId());
                                likeTv.setText(getString(R.string.like));
                                break;
                        }
                    }
                });
                if (domain.getData().getReCommandDynamic() != null &&
                        domain.getData().getReCommandDynamic().size() != 0) {
                    recommandListAdapter.refreshList(domain.getData().getReCommandDynamic());
                } else {
                    recommandListAdapter.clearList();
                }
                break;
        }
    }

    //设置喜欢
    public void set_dynamic_like(String token, Integer userDynamicId) {
        UserDynamicLikeNetImpl
                .set_like_dynamic(token, userDynamicId, token + "_set_like_dynamic_" + userDynamicId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //设置不喜欢
    public void set_dynamic_no_like(String token, Integer userDynamicId) {
        UserDynamicLikeNetImpl
                .set_no_like_dynamic(token, userDynamicId, token + "_set_dynamic_no_like_" + userDynamicId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //设置关注
    public void set_follow(String token, Integer userFollowId) {
        UserFollowNetImpl
                .set_follow(token, userFollowId, token + "_set_follow_" + userFollowId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //设置取消关注
    public void set_no_follow(String token, Integer userFollowId) {
        UserFollowNetImpl
                .set_no_follow(token, userFollowId, token + "_set_no_follow_" + userFollowId, new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    //发送动态评论
    public void send_dynamic_guest(String token, Integer userDynamicId,
                                   String userDynamicGuestContent, Dialog dialog) {
        UserDynamicGuestNetImpl
                .send_dynamic_guest(token, userDynamicId, userDynamicGuestContent,
                        token + "_send_dynamic_guest_" + userDynamicId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            dialog.dismiss();
                                            User onlineUser = UserService.getInstance(getApplicationContext()).getOnlineLoginUser();
                                            String token = "";
                                            if (onlineUser == null) {
                                                token = "";
                                            } else {
                                                token = onlineUser.getToken();
                                            }
                                            query_new_update_dynamic_guest(token, id);
//                                            Sneaker.with(DynamicDetailActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle("" + domain.getMessage(), R.color.white)
//                                                    .sneakSuccess();
                                            break;
                                        default:
//                                            Sneaker.with(DynamicDetailActivity.this)
//                                                    .autoHide(true)
//                                                    .setTitle("" + domain.getMessage(), R.color.white)
//                                                    .sneakError();
                                            showToast( domain.getMessage());
                                            break;
                                    }

                                }
                            }
                        });

    }


    //查询最新，热门动态评论
    public void query_new_update_dynamic_guest(String token, Integer userDynamicId
    ) {
        pageNow = 1;
        UserDynamicGuestNetImpl
                .query_new_update_dynamic_guest(token, userDynamicId, pageNow, pageSize,
                        token + "_query_new_update_dynamic_guest_" + userDynamicId + "_" + pageNow,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                bottomLoading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                bottomLoading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestDomain domain = gson.fromJson(response.body(), DynamicGuestDomain.class);
                                    if (domain.getData() != null &&
                                            domain.getData().getNewUpdateGuest() != null
                                            && domain.getData().getNewUpdateGuest().size() != 0) {
                                        noData.setVisibility(View.GONE);
                                        newUpdateTitle.setVisibility(View.VISIBLE);
                                        newUpdateAdpater.refreshList(domain.getData().getNewUpdateGuest());
                                    } else {
                                        newUpdateTitle.setVisibility(View.GONE);
                                        noData.setVisibility(View.VISIBLE);
                                    }
                                    if (domain.getData() != null &&
                                            domain.getData().getHotGuest() != null
                                            && domain.getData().getHotGuest().size() != 0) {
                                        hotTitle.setVisibility(View.VISIBLE);
                                        hotAdpater.refreshList(domain.getData().getHotGuest());
                                    } else {
                                        hotTitle.setVisibility(View.GONE);
                                    }

                                }
                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestDomain domain = gson.fromJson(response.body(), DynamicGuestDomain.class);
                                    if (domain.getData() != null &&
                                            domain.getData().getNewUpdateGuest() != null
                                            && domain.getData().getNewUpdateGuest().size() != 0) {
                                        noData.setVisibility(View.GONE);
                                        newUpdateTitle.setVisibility(View.VISIBLE);
                                        newUpdateAdpater.refreshList(domain.getData().getNewUpdateGuest());
                                    } else {
                                        newUpdateTitle.setVisibility(View.GONE);
                                        noData.setVisibility(View.VISIBLE);
                                    }
                                    if (domain.getData() != null &&
                                            domain.getData().getHotGuest() != null
                                            && domain.getData().getHotGuest().size() != 0) {
                                        hotTitle.setVisibility(View.VISIBLE);
                                        hotAdpater.refreshList(domain.getData().getHotGuest());
                                    } else {
                                        hotTitle.setVisibility(View.GONE);
                                    }

                                }
                            }
                        });

    }

    //分页最新动态评论,追加
    public void query_new_update_dynamic_guest_append(String token, Integer userDynamicId
    ) {

        pageNow++;
        UserDynamicGuestNetImpl
                .query_new_update_dynamic_guest(token, userDynamicId, pageNow, pageSize,
                        token + "_query_new_update_dynamic_guest_" + userDynamicId,
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                isMoreLoading = true;
                                bottomLoading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                isMoreLoading = false;
                                bottomLoading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !isFinishing()) {
                                    Gson gson = new Gson();
                                    DynamicGuestDomain domain = gson.fromJson(response.body(), DynamicGuestDomain.class);
                                    if (domain.getData() != null &&
                                            domain.getData().getNewUpdateGuest() != null
                                            && domain.getData().getNewUpdateGuest().size() != 0) {
                                        newUpdateAdpater.appendList(domain.getData().getNewUpdateGuest());
                                    }
                                }
                            }


                        });

    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation.getErrorCode() == 0) {
            city = aMapLocation.getCity();
            area = aMapLocation.getDistrict();
            if (aMapLocation.getAddress().length() <= 9) {
                fromAddress = aMapLocation.getAddress();
            } else {
                fromAddress = aMapLocation.getAddress().substring(9, aMapLocation.getAddress().length());
            }
            longitude = aMapLocation.getLongitude();
            latitude = aMapLocation.getLatitude();
        } else {
            showToast(aMapLocation.getErrorInfo());
        }

    }
    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void savetoImg(Bitmap bitmap) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            showLoading();
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File file = new File(Environment.getExternalStorageDirectory().getPath(), getString(R.string.app_name));
            if (!file.exists()) {   //判断文件夹是否存在，不存在则创建
                file.mkdirs();
            }
            String fileName = "";
            fileName = UUID.randomUUID().toString().substring(0, 4) + ".jpg";
            String com_file = file.getPath() + "/" + fileName;
            boolean isSuccess = RxImageTool.save(bitmap, com_file, Bitmap.CompressFormat.JPEG);
            if (isSuccess) {
                // 把文件插入到系统图库
                try {
                    String s = MediaStore.Images.Media.insertImage(getContentResolver(), com_file, fileName, "分享图片");

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + com_file));
                // 通知图库更新
                sendBroadcast(intent);

                ToolsUtils.shareImage(this, new File(com_file));
            } else {
                showToast("save error");
            }
            dissmissLoading();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }
    public synchronized void openMapDialog(String fromAddress, String toaddress, String fromlon, String fromlat, String tolon, String tolat) {
        BottomDialog mapDialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_select_nav_map)
                .setCancelOutside(false)
                .setDimAmount(0.4f)
                .setTag("mapDialog");
        mapDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.findViewById(R.id.cancel)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mapDialog.dismiss();
                            }
                        });
                v.findViewById(R.id.amap_bt)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mapDialog.dismiss();
                                OpenLocalMapUtil.openGaoDeMap(getApplicationContext(),
                                        getString(R.string.app_name),
                                        fromlat,
                                        fromlon,
                                        tolat,
                                        tolon);
                            }
                        });
                v.findViewById(R.id.baidu_bt)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                mapDialog.dismiss();
                                double[] from = OpenLocalMapUtil.gaoDeToBaidu(Double.parseDouble(fromlon), Double.parseDouble(fromlat));
                                double[] to = OpenLocalMapUtil.gaoDeToBaidu(Double.parseDouble(tolon), Double.parseDouble(tolat));
                                OpenLocalMapUtil.openBaiDuMap(
                                        fromAddress, toaddress, getApplicationContext(),
                                        getString(R.string.app_name),
                                        from[0] + "",
                                        from[1] + "",
                                        to[0] + "",
                                        to[1] + "");
                            }
                        });
                v.findViewById(R.id.tencent_bt)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mapDialog.dismiss();
                                double[] from = OpenLocalMapUtil.gaoDeToBaidu(Double.parseDouble(fromlon), Double.parseDouble(fromlat));
                                double[] to = OpenLocalMapUtil.gaoDeToBaidu(Double.parseDouble(tolon), Double.parseDouble(tolat));

                                double[] from_t = OpenLocalMapUtil.map_bd2tx(from[1], from[0]);
                                double[] to_t = OpenLocalMapUtil.map_bd2tx(to[1], to[0]);

                                OpenLocalMapUtil.openTencentMap(getApplicationContext(),
                                        getString(R.string.app_name),
                                        fromAddress,
                                        toaddress,
                                        from_t[0] + "",
                                        from_t[1] + "",
                                        to_t[0] + "",
                                        to_t[1] + "");
                            }
                        });
            }
        });
        mapDialog.show();
    }


}
